package com.agileai.portal.controller.forum;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.core.ResourceUploadService;
import com.agileai.hotweb.controller.core.FileUploadHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.wcm.WcmGeneralGroup8ContentManage;
import com.agileai.util.DateUtil;

public class ForumPostImgResouceUploaderHandler
        extends FileUploadHandler {
	
    private static final String ResourceGroupId = "1F348C89-F073-4B1F-8720-E6FFCD4BC80B";

    public ForumPostImgResouceUploaderHandler() {
        super();
    }
    public ViewRenderer prepareDisplay(DataParam param) {
        String grpId = ResourceGroupId;
        WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
        DataParam queryParam = new DataParam("GRP_ID", grpId);
        DataRow row = resourseManage.queryTreeRecord(queryParam);
        String resTypeDesc = row.stringValue("GRP_RES_TYPE_DESC");
        String resTypeExts = row.stringValue("GRP_RES_TYPE_EXTS");
        String resSizeLimit = row.stringValue("GRP_RES_SIZE_LIMIT");

        this.setAttribute("BIZ_ID", param.get("BIZ_ID"));
        this.setAttribute("GRP_ID", grpId);
        this.setAttribute("GRP_RES_TYPE_DESC", resTypeDesc);
        this.setAttribute("GRP_RES_TYPE_EXTS", resTypeExts);
        this.setAttribute("GRP_RES_SIZE_LIMIT", resSizeLimit);

        return new LocalRenderer(getPage());
    }

    @SuppressWarnings("rawtypes")
    @PageAction
    public ViewRenderer uploadFile(DataParam param) {
        String responseText = "";
        JSONObject jsonObject = new JSONObject();
        String location =null;
        String bizId =null;
        try {
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload fileFileUpload = new ServletFileUpload(fac);
            fileFileUpload.setHeaderEncoding("utf-8");

            List fileList = null;
            fileList = fileFileUpload.parseRequest(request);

            Iterator it = fileList.iterator();
            String name = "";
            String fileFullPath = null;
            File filePath = this.buildResourseSavePath("postMessage");

            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();

                    if (fieldName.equals("BIZ_ID")) {
                        bizId = item.getString();
                        resourceParam.put("BIZ_ID", bizId);
                    }

                    continue;
                }

                name = item.getName();
				
                resourceParam.put("GRP_ID", ResourceGroupId);
                resourceParam.put("RES_NAME", name);
                
                String suffix = name.substring(name.lastIndexOf("."));

                String enName = KeyGenerator.instance().genShortKey() + suffix;
                location = resourceRelativePath + "/" + enName;
                resourceParam.put("RES_LOCATION", location);
                jsonObject.put("url", location);
                fileFullPath = filePath.getAbsolutePath() + File.separator + enName;
                setAttribute("location",location);
                long resourceSize = item.getSize();
                resourceParam.put("RES_SIZE", String.valueOf(resourceSize));


                resourceParam.put("RES_SUFFIX", suffix);
                resourceParam.put("RES_SHAREABLE", "Y");

                File tempFile = new File(fileFullPath);

                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }

                item.write(tempFile);
                
                createThumbnail(tempFile);
                
                BufferedImage bufferedImage = ImageIO.read(tempFile);   
				String width = String.valueOf(bufferedImage.getWidth());
				String height = String.valueOf(bufferedImage.getHeight());
				resourceParam.put("RES_WIDTH",width);
				resourceParam.put("RES_HEIGHT",height);
				jsonObject.put("width", width);
				jsonObject.put("height", height);
                this.insertResourceRecord();
            }
            responseText = jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new AjaxRenderer(responseText);
    }
    
    protected File buildResourseSavePath(String columnId){
		File result = null;
		File contextFile = new File(System.getProperty("catalina.base")+"/webapps");
		String parentAbsolutePath = contextFile.getAbsolutePath();
		String resourseFilePath = parentAbsolutePath+File.separator+"HotServer"
				+File.separator+"reponsitory"+File.separator+"resourse"+File.separator +columnId
				+File.separator+DateUtil.getYear()+File.separator+DateUtil.getMonth();
		
		resourceRelativePath = "/HotServer"+"/reponsitory"+"/resourse/"+columnId
				+"/"+DateUtil.getYear()+"/"+DateUtil.getMonth();
		result = new File(resourseFilePath);
		return result;
	}

	private void insertResourceRecord() {
        WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
        resourseManage.createtContentRecord("WcmGeneralResource", resourceParam);

        String resId = resourceParam.get("RES_ID");
        String bizId = resourceParam.get("BIZ_ID");
        ResourceUploadService resourceUploadService = getResourceUploadService();
        resourceUploadService.createResourceRelation(bizId, resId);
    }

    private ResourceUploadService getResourceUploadService() {
        return (ResourceUploadService) this.lookupService("forumPostImgResouceUploaderService");
    }
    
    public void createThumbnail(File srcFile){
		try {
			String imageName = srcFile.getName();
			File desFileDir = new File(srcFile.getParentFile().getAbsolutePath()+"/thumbnail/");
			if (!desFileDir.exists()){
				desFileDir.mkdirs();
			}
			File newDesFilew =  new File(desFileDir.getAbsolutePath()+"/"+imageName);
			Thumbnails.of(srcFile).size(126, 126).toFile(newDesFilew);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
